import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, message, Modal, Space, Tag, Popconfirm, Table } from 'antd';
import React, { useRef, useState } from 'react';
import { api } from '@/services/api';
import type { User } from '@/services/generated/models';
import UserForm from './components/UserForm';
import DeviceManageModal from './components/DeviceManageModal';
import { useAccess, Access } from '@umijs/max';

const UsersPage: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [devicesModalVisible, setDevicesModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState<User>();
  const actionRef = useRef<ActionType>();
  const access = useAccess();

  // 表格列定义
  const columns: ProColumns<User>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      copyable: true,
    },
    {
      title: '姓名',
      dataIndex: 'firstName',
      search: false,
      render: (_, record) => {
        const firstName = record.firstName || '';
        const lastName = record.lastName || '';
        const fullName = `${lastName} ${firstName}`.trim();
        return fullName || '-';
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      search: false,
      copyable: true,
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      valueEnum: {
        true: { text: '启用', status: 'Success' },
        false: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '员工',
      dataIndex: 'isStaff',
      valueEnum: {
        true: { text: '是员工', status: 'Success' },
        false: { text: '不是员工', status: 'Default' },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => {
        // 如果当前用户是超级管理员，或者目标用户不是超级管理员，则显示操作按钮
        const canOperate = access.isSuperuser || !record.isSuperuser;
        return [
          <Access key="edit" accessible={access.canChangeUser && canOperate}>
            <a
              onClick={() => {
                console.log('edit', record);
                setCurrentUser(record);
                setEditModalVisible(true);
              }}
            >
              编辑
            </a>
          </Access>,
          <Access key="devices" accessible={access.canChangeUser && canOperate}>
            <a
              onClick={() => {
                setCurrentUser(record);
                setDevicesModalVisible(true);
              }}
              style={{ marginLeft: 8 }}
            >
              设备管理
            </a>
          </Access>,
          <Access key="delete" accessible={access.canDeleteUser && canOperate}>
            <Popconfirm
              title="确定要删除该用户吗？"
              onConfirm={async () => {
                try {
                  await api.accounts.accountsUsersDestroy({ id: record.id });
                  message.success('删除成功');
                  actionRef.current?.reload();
                } catch (error) {
                  message.error('删除失败');
                }
              }}
            >
              <a>删除</a>
            </Popconfirm>
          </Access>,
        ];
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<User>
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
          defaultCollapsed: false,
        }}
        toolBarRender={() => [
          <Access key="add" accessible={access.canAddUser}>
            <Button
              type="primary"
              onClick={() => setCreateModalVisible(true)}
            >
              <PlusOutlined /> 新建用户
            </Button>
          </Access>,
        ]}
        request={async (params) => {
          const { current, pageSize, username, email, isActive, isStaff, ...restParams } = params;
          try {
            const users = await api.accounts.accountsUsersList({
              username,
              email,
              isActive: isActive !== undefined ? isActive === 'true' : undefined,
              isStaff: isStaff !== undefined ? isStaff === 'true' : undefined,
              ordering: params.order ? `${params.order === 'descend' ? '-' : ''}${params.field}` : undefined,
            });
            
            return {
              data: users,
              success: true,
              total: users.length,
            };
          } catch (error) {
            message.error('获取用户列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        rowSelection={
          access.canChangeUser || access.canDeleteUser
            ? {
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
              }
            : undefined
        }
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
          // 过滤掉超级管理员用户，除非当前用户也是超级管理员
          const operableRows = selectedRows.filter(
            row => access.isSuperuser || !row.isSuperuser
          );
          return (
            <Space size={16}>
              <Access accessible={access.canDeleteUser}>
                <a
                  onClick={() => {
                    Modal.confirm({
                      title: '批量删除',
                      content: `确定要删除选中的 ${operableRows.length} 个用户吗？`,
                      okType: 'danger',
                      onOk: async () => {
                        try {
                          await Promise.all(
                            operableRows.map(row =>
                              api.accounts.accountsUsersDestroy({ id: row.id })
                            )
                          );
                          message.success('批量删除成功');
                          onCleanSelected();
                          actionRef.current?.reload();
                        } catch (error) {
                          message.error('批量删除失败');
                        }
                      },
                    });
                  }}
                >
                  批量删除
                </a>
              </Access>
              <Access accessible={access.canChangeUser}>
                <a
                  onClick={() => {
                    Modal.confirm({
                      title: '批量启用',
                      content: `确定要启用选中的 ${operableRows.length} 个用户吗？`,
                      onOk: async () => {
                        try {
                          await Promise.all(
                            operableRows.map(row =>
                              api.accounts.accountsUsersPartialUpdate({
                                id: row.id,
                                patchedUserRequest: { isActive: true },
                              })
                            )
                          );
                          message.success('批量启用成功');
                          onCleanSelected();
                          actionRef.current?.reload();
                        } catch (error) {
                          message.error('批量启用失败');
                        }
                      },
                    });
                  }}
                >
                  批量启用
                </a>
              </Access>
              <Access accessible={access.canChangeUser}>
                <a
                  onClick={() => {
                    Modal.confirm({
                      title: '批量禁用',
                      content: `确定要禁用选中的 ${operableRows.length} 个用户吗？`,
                      onOk: async () => {
                        try {
                          await Promise.all(
                            operableRows.map(row =>
                              api.accounts.accountsUsersPartialUpdate({
                                id: row.id,
                                patchedUserRequest: { isActive: false },
                              })
                            )
                          );
                          message.success('批量禁用成功');
                          onCleanSelected();
                          actionRef.current?.reload();
                        } catch (error) {
                          message.error('批量禁用失败');
                        }
                      },
                    });
                  }}
                >
                  批量禁用
                </a>
              </Access>
            </Space>
          );
        }}
      />

      <Access accessible={access.canAddUser}>
        <UserForm
          visible={createModalVisible}
          onVisibleChange={setCreateModalVisible}
          onSuccess={() => {
            setCreateModalVisible(false);
            actionRef.current?.reload();
          }}
        />
      </Access>

      <Access accessible={access.canChangeUser}>
        <UserForm
          visible={editModalVisible}
          onVisibleChange={setEditModalVisible}
          user={currentUser}
          onSuccess={() => {
            setEditModalVisible(false);
            actionRef.current?.reload();
          }}
        />
      </Access>

      <DeviceManageModal
        visible={devicesModalVisible}
        onVisibleChange={setDevicesModalVisible}
        userId={currentUser?.id}
        onSuccess={() => {
          actionRef.current?.reload();
        }}
      />
    </PageContainer>
  );
};

export default UsersPage;
